//
//  RefreshTableView.m
//  XinDong
//
//  Created by tt on 12-11-9.
//  Copyright (c) 2012年 HengYongKeJi. All rights reserved.
//

#import "RefreshTableView.h"

@implementation RefreshTableView
@synthesize hasMore = _hasMore;
@synthesize dataArrayCount = _dataArrayCount;
@synthesize refreshDataSource = _refreshDataSource;
@synthesize refreshDelegate = _refreshDelegate;
@synthesize footerRefreshState = _footerRefreshState;

- (id)initWithFrame:(CGRect)frame style:(UITableViewStyle)style
{
    self = [super initWithFrame:frame style:style];
    if (self) {
        _hasMore = YES;
        self.delegate = self;
        self.dataSource = self;
        [self addHeadRefreshView];
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
    }
    return self;
}

- (void)addHeadRefreshView
{
    if(_headRefreshView){
        [_headRefreshView removeFromSuperview];
        _headRefreshView = nil;
    }
    _headRefreshView = [[RefreshView alloc] initWithFrame:CGRectMake(0.0f, -240.f, 320.f, 240.f) position:RefreshViewTop];
    _headRefreshView.delegate = self;
    [self addSubview:_headRefreshView];
}

#pragma mark - UITableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = indexPath.row;
    if(row == _dataArrayCount && _hasMore){
        return 50.f;
    }else{
        if([_refreshDelegate respondsToSelector:@selector(heightForRowAtIndexPath:)]){
            return [_refreshDelegate heightForRowAtIndexPath:indexPath];
        }
    }
    return 0.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if([_refreshDelegate respondsToSelector:@selector(heightForHeaderInSection:)]){
        return [_refreshDelegate heightForHeaderInSection:section];
    }
    return 0.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if([_refreshDelegate respondsToSelector:@selector(heightForFooterInSection:)]){
        return [_refreshDelegate heightForFooterInSection:section];
    }
    return 0.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if([_refreshDelegate respondsToSelector:@selector(viewForHeaderInSection:)]){
        return [_refreshDelegate viewForHeaderInSection:section];
    }
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    if([_refreshDelegate respondsToSelector:@selector(viewForFooterInSection:)]){
        return [_refreshDelegate viewForFooterInSection:section];
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == _dataArrayCount && _hasMore){
        return;
    }
    if([_refreshDelegate respondsToSelector:@selector(didSelectRowAtIndexPath:)]){
        [_refreshDelegate didSelectRowAtIndexPath:indexPath];
    }
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if([_refreshDataSource respondsToSelector:@selector(numberOfRowsInSection:)]){
        return _hasMore?[_refreshDataSource numberOfRowsInSection:section]+1:[_refreshDataSource numberOfRowsInSection:section];
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"refreshTableCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    
    for (UIView *subview in cell.contentView.subviews) {
        [subview removeFromSuperview];
    }
    int row = indexPath.row;
    if(row < _dataArrayCount){
        cell = [_refreshDataSource cellForRowAtIndexPath:indexPath];
    }else if(row == _dataArrayCount && _hasMore){
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, FootViewHeight)];
        _footerView.backgroundColor = [UIColor clearColor];
        [cell.contentView addSubview:_footerView];
        
        _footerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 85, FootViewHeight)];
        _footerLabel.backgroundColor = [UIColor clearColor];
        _footerLabel.font = [UIFont systemFontOfSize:14];
        _footerLabel.textAlignment = UITextAlignmentCenter;
        _footerLabel.textColor = [UIColor blackColor];
        _footerLabel.text = @"上拉加载更多";
        _footerLabel.center = CGPointMake(_footerView.center.x, _footerLabel.center.y);
        [_footerView addSubview:_footerLabel];
        
        _footerActivityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        _footerActivityIndicator.center = CGPointMake(_footerLabel.frame.origin.x + _footerLabel.frame.size.width + 5 , 25);
        _footerActivityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [_footerView addSubview:_footerActivityIndicator];
        
        if(_footerRefreshState == RefreshLoading){
            _footerLabel.text = @"正在加载中...";
            [_footerActivityIndicator startAnimating];
            _footerActivityIndicator.hidden = NO;
        }

    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if([_refreshDataSource respondsToSelector:@selector(numberOfSectionsInTableView)]){
        return [_refreshDataSource numberOfSectionsInTableView];
    }
    return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if([_refreshDataSource respondsToSelector:@selector(titleForHeaderInSection:)]){
        return [_refreshDataSource titleForHeaderInSection:section];
    }
    return nil;
}

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
    if([_refreshDataSource respondsToSelector:@selector(titleForFooterInSection:)]){
        [_refreshDataSource titleForFooterInSection:section];
    }
    return nil;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    if([_refreshDataSource respondsToSelector:@selector(canEditRowAtIndexPath:)]){
        return [_refreshDataSource canEditRowAtIndexPath:indexPath];
    }else{
        return NO;
    }
}

-(void)tableView:(UITableView*)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath*)indexPath
{
    if([_refreshDataSource respondsToSelector:@selector(commitEditingStyle:forRowAtIndexPath:)]){
        [_refreshDataSource commitEditingStyle:editingStyle forRowAtIndexPath:indexPath];
    }
}
#pragma mark - UIScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [_headRefreshView refreshScrollViewDidScroll:scrollView];
    if (_hasMore) {
        if(scrollView.contentOffset.y > (scrollView.contentSize.height - scrollView.frame.size.height + 30) && scrollView.dragging && scrollView.tracking){
            if (_footerRefreshState == RefreshNormal) {
                _footerRefreshState = RefreshPulling;
                if (_footerView) {
                    _footerLabel.text = @"可以松开了";
                    [_footerActivityIndicator startAnimating];
                    _footerActivityIndicator.hidden = YES;
                }
            }
        }else if (scrollView.contentOffset.y < (scrollView.contentSize.height - scrollView.frame.size.height + 30) && scrollView.dragging && scrollView.tracking) {
            if (_footerRefreshState == RefreshPulling) {
                _footerRefreshState = RefreshNormal;
                if (_footerView) {
                    _footerLabel.text = @"上拉加载更多";
                    [_footerActivityIndicator stopAnimating];
                    _footerActivityIndicator.hidden = YES;
                }
            }
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    if(_hasMore && _footerRefreshState == RefreshPulling){
        _footerRefreshState = RefreshNormal;
        if (_footerView) {
            _footerLabel.text = @"上拉加载更多";
            [_footerActivityIndicator stopAnimating];
            _footerActivityIndicator.hidden = YES;
        }
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_headRefreshView refreshScrollViewDidEndDragging:scrollView];
    if(_hasMore && scrollView.contentOffset.y >= (scrollView.contentSize.height-scrollView.frame.size.height + 30)){
        if(_footerRefreshState == RefreshPulling){
            _footerRefreshState = RefreshLoading;
            if (_footerView) {
                _footerLabel.text = @"正在加载中...";
                [_footerActivityIndicator startAnimating];
                _footerActivityIndicator.hidden = NO;
            }
            if([_refreshDelegate respondsToSelector:@selector(getMoreData)]){
                [_refreshDelegate getMoreData];
            }
        }
    }
}

#pragma mark - Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	_headRefreshing = YES;
    if([_refreshDelegate respondsToSelector:@selector(getUpData)]){
        [_refreshDelegate getUpData];
    }
}

- (void)doneLoadingTableViewData{
	_headRefreshing = NO;
	[_headRefreshView refreshScrollViewDataSourceDidFinishedLoading:self];
	[self reloadData];
}

#pragma mark - RefreshDelegate

- (void)refreshDidTriggerRefresh:(RefreshView*)view {
	[self reloadTableViewDataSource];
}

- (BOOL)refreshDataSourceIsLoading:(RefreshView*)view {
	return _headRefreshing;
}

- (NSDate*)refreshTableHeaderDataSourceLastUpdated:(RefreshView*)view{
	
	return [NSDate date]; // should return date data source was last changed
	
}
@end
